#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include "log.hpp"
#include "lockguard.hpp"

void useTips(char *command)
{
    std::cout << "useTips:" << command << " ip" << " port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
        useTips(argv[0]);

    // 1、创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1)
    {
        LOG(FATAL, "socket is failed!");
        exit(1);
    }

    // 2、创建本地网络信息：套接字不需要显示的绑定网络信息，当第一次通信的时候，会自动绑定
    // 防止端口冲突

    // 3、创建要连接的服务器网络信息
    struct sockaddr_in destaddr;
    destaddr.sin_family = AF_INET;
    destaddr.sin_port = htons(std::stoi(argv[2]));
    destaddr.sin_addr.s_addr = inet_addr(argv[1]);

    // 4、连接服务器
    connect(sockfd, (struct sockaddr *)&destaddr, sizeof(destaddr));

    // 5、发送
    while (true)
    {
        cout << "enter#:";
        string msg = "";
        getline(cin, msg);
        // 和sendto用法一样，只不过后面少了发送这的套接字，因为tcp是面向连接的，已经连接好了
        int ret = send(sockfd, msg.c_str(), msg.size(), 0);
        if (ret > 0)
        {
            char buf[1024] = {0};
            ret = recv(sockfd, buf, sizeof(buf), 0); //用发和recvfrom一样
            if(ret > 0)
            {
                LOG(INFO, "echo:%s\n", buf);
            }
        }
        else
        {
            LOG(ERROR, "send is failed!\n");
        }
    }

    return 0;
}